<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="用户" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择用户" filterable clearable>
          <el-option
            v-for="data in userList"
            :key="data.id"
            :label="data.name"
            :value="data.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="代理" prop="proxyId">
        <el-select v-model="queryParams.proxyId" placeholder="请选择代理" filterable clearable>
          <el-option
            v-for="data in proxyUserList"
            :key="data.id"
            :label="data.name"
            :value="data.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.proxy_account_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['proxy:account:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['proxy:account:edit']"
        >修改</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['proxy:account:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['proxy:account:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center"   />-->
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="代理id" align="center" prop="proxyId" />
      <el-table-column label="账号" align="center" prop="account" />
      <el-table-column label="密码" align="center" prop="password" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.proxy_account_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="流量上限" align="center" prop="limitFlow" >
        <template slot-scope="scope">
          <span v-if="scope.row.limitFlow < 0">{{scope.row.limitFlow}}M</span>
          <span v-if="scope.row.limitFlow == 0">不限制</span>
          <span v-if="scope.row.limitFlow >0 ">{{mFormatFlow(scope.row.limitFlow)}}</span>
        </template>
      </el-table-column>

      <el-table-column label="消耗流量" align="center" prop="consumedFlow" >
        <template slot-scope="scope">
          <span v-if="scope.row.consumedFlow < 1000">{{scope.row.consumedFlow}}M</span>
          <span v-if="scope.row.consumedFlow >= 1000">
            {{mFormatFlow(scope.row.consumedFlow)}}  </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['proxy:account:edit']"
            v-if="scope.row.proxyId !=null && scope.row.userId !=null  "
          >修改</el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="chargeFlow(scope.row)"
            v-hasPermi="['proxy:account:charge_flow']"
            v-if="scope.row.proxyId !=null && scope.row.userId !=null "
          >充值流量</el-button>


          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="reduceFlow(scope.row)"
            v-hasPermi="['proxy:account:reduce_flow']"
            v-if="scope.row.proxyId !=null && scope.row.userId !=null "
          >扣除流量</el-button>



<!--          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['proxy:account:remove']"
          >删除</el-button>-->


        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理账号对话框 -->
    <el-dialog title="添加代理账号" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="rules" label-width="100px">
        <el-form-item label="后台登录账号" prop="account">
          <el-input v-model="addForm.account" placeholder="请输入后台登录账号" />
        </el-form-item>
        <el-form-item label="后台登录密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入后台登录密码" />
        </el-form-item>
        <el-form-item label="状态" prop="state" >
          <el-select v-model="addForm.state" placeholder="请选择状态" disabled>
            <el-option
              v-for="dict in dict.type.proxy_account_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流量(G)" prop="limitFlow">
          <el-input v-model="addForm.limitFlowG" placeholder="请输入流量上限(G)"/>
          <span>
            实际 {{addForm.limitFlow}} M (<span style="color:red">0为不限制</span>)
            <span v-if="addForm.limitFlowG >=1000"> {{ (addForm.limitFlowG/1000).toFixed(3) }} T </span>
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <el-dialog title="编辑代理信息 " :visible.sync="editOpen" width="500px" append-to-body>
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="editForm.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="editForm.state" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.proxy_account_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流量(G)" prop="limitFlow">
          <el-input v-model="editForm.limitFlowG"  placeholder="请输入流量上限(G)" disabled />
          <span>
            实际 {{editForm.limitFlow}} M (<span style="color:red">0为不限制</span>)
            <span v-if="editForm.limitFlowG >= 1000"> {{ (editForm.limitFlowG/1000).toFixed(3) }} T </span>
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="流量充值 " :visible.sync="chargeFlowOpen" width="500px" append-to-body>
      <el-form ref="chargeFlowForm" :model="chargeFlowForm" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="chargeFlowForm.account" placeholder="请输入账号" disabled />
        </el-form-item>
        <el-form-item label="流量(G)" prop="flowG">
          <el-input v-model="chargeFlowForm.flowG" placeholder="请输入流量上限(G)"  />
          <span>
            实际 {{chargeFlowForm.flow}} M
            <span v-if="chargeFlowForm.flowG >= 1000"> {{ (chargeFlowForm.flowG/1000).toFixed(3) }} T </span>
          </span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chargeFlowSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="流量扣减 " :visible.sync="reduceFlowOpen" width="500px" append-to-body>
      <el-form ref="reduceFlowForm" :model="reduceFlowForm" :rules="rules" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="reduceFlowForm.account" placeholder="请输入账号" disabled />
        </el-form-item>
        <el-form-item label="流量(G)" prop="flowG">
          <el-input v-model="reduceFlowForm.flowG" placeholder="请输入流量上限(G)"  />
          <span>
            实际 {{reduceFlowForm.flow}} M
            <span v-if="reduceFlowForm.flowG >= 1000"> {{ (reduceFlowForm.flowG/1000).toFixed(3) }} T </span>
          </span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="reduceFlowSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAccount,
  getAccount,
  delAccount,
  addAccount,
  updateAccount,
  chargeFlow,
  reduceFlow,
  proxyAccountList,
  userList
} from "@/api/proxy/account";
import {mFormatFlow} from "@/utils/ruoyi";

export default {
  name: "Account",
  dicts: ['proxy_account_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理账号表格数据
      accountList: [],
      proxyUserList:[],
      userList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      addOpen: false,
      editOpen: false,
      chargeFlowOpen: false,
      reduceFlowOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        proxyId: null,
        account: null,
        password: null,
        state: null,
        limitFlow: null,
      },
      // 表单参数
      addForm:{
        limitFlowG:null,
        limitFlow:null,
        state:"1"
      },
      editForm: {},


      chargeFlowForm:{
        flowG:0.001
      },
      reduceFlowForm:{
        flowG:0.001
      },

      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getUserList();
    this.getProxyUserList();
    this.getList();
  },
  watch:{
    // 1G = 1000M
    'editForm.limitFlowG': function(newVal) {
      if(newVal!=null) {
        this.editForm.limitFlow = parseInt(newVal * 1000);
      }
    },
    'addForm.limitFlowG': function(newVal) {
      if(newVal!=null){
        this.addForm.limitFlow = parseInt(newVal * 1000);
      }
    },

    'chargeFlowForm.flowG': function(newVal) {
      if(newVal!=null) {
        this.chargeFlowForm.flow = parseInt(newVal * 1000);
      }
    },

    'reduceFlowForm.flowG': function(newVal) {
      if(newVal!=null) {
        this.reduceFlowForm.flow =parseInt(newVal * 1000);
      }
    }
  },
  methods: {
    mFormatFlow,
    getProxyUserList(){
      proxyAccountList().then(response => {
        this.proxyUserList=  response.data;
      })
    },
    getUserList(){
      userList().then(response => {
        this.userList=  response.data;
      })
    },

    /** 查询代理账号列表 */
    getList() {
      this.loading = true;
      listAccount(this.queryParams).then(response => {
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.editOpen = false;
      this.addOpen = false;
      this.chargeFlowOpen =false
      this.reduceFlowOpen =false
      this.reset();
    },
    // 表单重置
    reset() {
      this.addForm = {
        account: null,
        password: null,
        remark: null,
        createTime: null,
        limitFlowG:null,
        limitFlow:null,
        state:"1"
      };
      this.editForm = {
        account: null,
        password: null,
        remark: null,
        createTime: null,
        limitFlowG:null,
        limitFlow:null,
        state:null
      };

      this.chargeFlowForm={
      };
      this.reduceFlowForm={
      };
      this.resetForm("addForm");
      this.resetForm("editForm");
      this.resetForm("chargeFlowForm");
      this.resetForm("reduceFlowForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addOpen = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAccount(id).then(response => {
        this.editForm = response.data;
        console.info(response.data,response.data.limitFlow);
        this.editForm.limitFlowG =  (response.data.limitFlow / 1000).toFixed(3);
        this.editOpen = true;
      });
    },

    chargeFlow(row){
      const id = row.id || this.ids
      getAccount(id).then(response => {
        this.reset();
        this.chargeFlowForm.account = response.data.account;
        this.chargeFlowForm.proxyAccountId = id;
         this.chargeFlowOpen =true
      });
    },
    reduceFlow(row){
      const id = row.id || this.ids
      getAccount(id).then(response => {
        this.reset();
        this.reduceFlowForm.account = response.data.account;
        this.reduceFlowForm.proxyAccountId = id;
        this.reduceFlowOpen =true
      });
    },


    addSubmitForm(){
      this.$refs["addForm"].validate(valid => {
        if (valid) {

          //判断非空字段
          if(   this.addForm.limitFlow==null){
            this.$modal.msgError("流量不能为空");
            return ;
          }

          if(this.addForm.account==null || this.addForm.password==null ){
            this.$modal.msgError("登录用户名密码不能为空");
            return ;
          }

          addAccount(this.addForm).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.addOpen = false;
            this.getList();
          });
        }
      });
    },
    editSubmitForm(){
      this.$refs["editForm"].validate(valid => {
        if (valid) {
            updateAccount(this.editForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editOpen = false;
              this.getList();
            });
        }
      });
    },

    chargeFlowSubmitForm(){
      this.$refs["chargeFlowForm"].validate(valid => {
        if (valid) {
          if( this.chargeFlowForm.flow==null || this.chargeFlowForm.flow<=0){
            this.$modal.msgError("流量不能为空或小于等于0");
            return ;
          }
          chargeFlow(this.chargeFlowForm).then(response => {
            this.$modal.msgSuccess("充值流量成功");
            this.chargeFlowOpen = false;
            this.getList();
          });
        }
      });
    },
    reduceFlowSubmitForm(){
      this.$refs["reduceFlowForm"].validate(valid => {
        if (valid) {
          if( this.reduceFlowForm.flow==null || this.reduceFlowForm.flow<=0){
            this.$modal.msgError("流量不能为空或小于等于0");
            return ;
          }
          reduceFlow(this.reduceFlowForm).then(response => {
            this.$modal.msgSuccess("扣除流量成功");
            this.reduceFlowOpen = false;
            this.getList();
          });
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除代理账号编号为"' + ids + '"的数据项？').then(function() {
        return delAccount(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('proxy/account/export', {
        ...this.queryParams
      }, `account_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
